#!coding:utf-8
'''
Created on Oct 11, 2012

@author: join
'''
from django.http import HttpResponse
from django.db import connection
import datetime
from lottery_terminal.common import utils
import json
import logging
from lottery_terminal.common.ticketutil import pre_stop_dict
from lottery_terminal.service.lotteryservice.baseService import BaseLottery
#from lottery_terminal.common import Constant
LOG = logging.getLogger('terminal')

def _do_init(lotterycode,pre_stop):
    result = {}
    try:
        baselottery = BaseLottery(lotterycode)
        period,status = baselottery.get_current_period(pre_stop)
        period.endtime += datetime.timedelta(minutes=-pre_stop) #双色球停止投注时间提前半小时
        result['msg'] = ''
        if status == 200:
            result['period'] = period
            result['msg'] = utils.convert_datetime_to_str(period.endtime, '%Y年%m月%d日 %H:%M:%S')
            if period.endtime<=datetime.datetime.now():
                return None,500
            seconds2awardtime = (period.endtime-datetime.datetime.now()).seconds
            result['seconds2awardtime'] = seconds2awardtime
        if status == 201:
            result['period'] = period
            result['msg'] = u'开奖中...'
            if period.awardtime<=datetime.datetime.now():
                return None,500
            seconds2awardtime = (period.awardtime-datetime.datetime.now()).seconds + pre_stop
            result['seconds2awardtime'] = seconds2awardtime
        return result
    except Exception as e:
        LOG.exception('an exception occured:%s' % e)
        return None,500
    
    
@utils.ajaxrender
def init_period(req):
    '''初始化彩票期次数据'''
    lotterycode = req.POST.get('type')
    result = _do_init(lotterycode,pre_stop_dict.get(lotterycode))
    if not result:
        return u'获取期次失败',500
    period = result['period']
    msg = result['msg']
    result2 = {'periodid':period.periodid,'enddate':msg,'msercond':result['seconds2awardtime']}
    return json.dumps(result2)


def query_period(request,lotterycode):
    try:
        baselottery = BaseLottery(lotterycode)
        result=baselottery.download_periods(lotterycode)
        if not result:
            return HttpResponse("error")
        if type(result.awardtime) is datetime.datetime:
            if result.awardtime<=datetime.datetime.now():
                return HttpResponse("error")
            seconds=(result.awardtime-datetime.datetime.now()).seconds
        else:
            seconds=(utils.format_datetime(result.awardtime)-datetime.datetime.now()).seconds
            if utils.format_datetime(result.awardtime)<=datetime.datetime.now():
                return HttpResponse("error")
        return HttpResponse('{"seconds":"%s","periodid":"%s"}' % (seconds,result.periodid))
    except Exception as e:
        LOG.exception("an exception occured:%s" % e)
        return HttpResponse("error")


def query_awardcode(request,lotterycode,periodid):
    lotterycode = '%s'%lotterycode
    periodid = '%s'%periodid
    try:
        baselottery = BaseLottery(lotterycode)
        award_money_data = baselottery.query_award_money(periodid)
#        awardcode = baselottery.query_award_code(periodid)
        if not award_money_data:
            return HttpResponse('error')
#        if lotterycode==Constant.SSQ_CODE:
        query_award_list = baselottery.query_award_list(periodid) #查询出所有中奖名单,更新其中奖金额，是否大奖到数据库
        if not query_award_list:
            return HttpResponse('error')
        return HttpResponse('ok')
    except Exception as e:
        LOG.exception("an exception occured:%s" % e)
        return HttpResponse('error')